<template>
  <video id="hlsVideo" ref="hlsVideo" muted="muted" preload="true"/>
</template>
<script>
import Hls from "hls.js";
export default {
  data() {
    return {
      hls: "",
    };
  },
  props: {
    url: {
      type: String,
      default: "",
    },
  },
  created: function () {
    let _this = this;
    _this.$once("hook:beforeDestroy", () => {
      _this.destroyHls();
    });
  },
  mounted: function () {

  },
  destroyed: function () {},
  methods: {
    destroyHls() {
      if (this.hls) {
        this.$refs.hlsVideo.pause();
        this.hls.destroy();
        this.hls = null;
      }
    },
    loadVideoFn() {
      console.log( this.$refs);
      if (Hls.isSupported()) {
        this.hls = new Hls();
        this.hls.loadSource(
          this.url
          // "http://127.0.0.1:10008/record/192.168.1.100/20220110/out.m3u8"
        );
        this.hls.attachMedia(this.$refs.hlsVideo);
        //  console.log(this.$refs.hlsVideo);
        this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
          console.log("加载成功");
          this.$refs.hlsVideo.play();
        });
        this.hls.on(Hls.Events.ERROR, (event, data) => {
          console.log(event, data);
          // 监听出错事件
          console.log("加载失败");
        });
      }
    }
  },
  watch: {
    url: {
      immediate: true,
      handler(val) {
        if (val) {
          this.loadVideoFn();
        }
      },
    },
  },
};
</script>
<style scoped>
#video-container,
#hlsVideo {
  width: 100%;
  height: 100%;
  border: 1px solid #ccc;
  overflow: hidden;
}
</style>